import { reqGetCode ,reqUserRegister ,reqUserLogin , reqUserInfo ,reqLogout } from "@/api";
const state = {
    code: '',
    token: localStorage.getItem('TOKEN'),//token每次都从localStorage取数据
    userInfo:{ },
};
const actions = {
    async getCode({ commit },phone ) {
        let res = await reqGetCode(phone);
        if (res.code == 200) {
            commit('GETCODE', res.data);
        }
    },

    async userRegister({ commit }, data) {
        let res = await reqUserRegister(data);
        if (res.code == 200) {
            return 'ok';
        }
        else { 
            return Promise.reject(new Error('faile'));
        }
    },

    //登录业务[token](令牌)
    async userLogin({ commit ,state}, data) {
        let res = await reqUserLogin(data);
        if (res.code == 200) {
            //服务器下发的token是区分用户的唯一标识
            commit('USERLOGIN', res.data.token);
            //会话存储一般可以用于传输复杂数据(路由跳转时，vuex一般是用于同页面不存在数据传输的问题)。
            localStorage.setItem("TOKEN",res.data.token);//本地存储一班来负责登陆业务，具有持久性
            return 'ok';
        } 
        else {
            console.log("登陆失败");
            return Promise.reject(new Error('faile'));
        }
    },

    //获取用户信息
    async getUserInfo({ commit }) {
        let res =await reqUserInfo();
        if (res.code == 200) {
            commit('GETUSERINFO', res.data);
            return 'ok';
        }
        else { 
            return Promise.reject(new Error("faile"));
        }
    },

    //退出登录
    async logOut() {
        let result = await reqLogout();
        if (result.code == 200) {
            localStorage.setItem('TOKEN', "");//制空或删除
            state.userInfo = {};//全部制空
            state.code = '';//页面显示有依赖，必须全部清楚
            state.token = '';
            return 'ok';
        }
        else {
            return Promise.reject(new Error('faile'));
        }
    }
};
const mutations = {
    GETCODE(state, code) {
        state.code = code;
    },
    USERLOGIN(state, data) {
        state.token = data;
    },
    GETUSERINFO(state, data) {
        state.userInfo = data;
    }
};


export default {
    state,
    actions,
    mutations
}